package com.dabai.markdownq;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.PopupMenu;
import androidx.core.content.FileProvider;
import androidx.core.view.GravityCompat;
import androidx.core.widget.NestedScrollView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dabai.dbutils.dialog.MdcDialog;
import com.dabai.dbutils.popup.menu.PopupMenuUtils;
import com.dabai.dbutils.toast.DBToast;
import com.dabai.dbutils.utils.DabaiUtils;
import com.dabai.dbutils.utils.DateUtils;
import com.dabai.dbutils.utils.FileUtils;
import com.dabai.dbutils.utils.NotificationUtils;
import com.dabai.dbutils.utils.SAFUtils;
import com.dabai.dbutils.utils.ShareUtils;
import com.dabai.dbutils.utils.SharedPreferencesBasicUse;
import com.dabai.dbutils.utils.SharedPreferencesUtils;
import com.dabai.dbutils.utils.StringUtils;
import com.dabai.dbutils.utils.component.ActivityUtils;
import com.dabai.markdownq.adapter.FileAdapter;
import com.dabai.markdownq.bean.FileData;
import com.dabai.markdownq.databinding.ActivityMainBinding;
import com.dabai.markdownq.ui.EditorActivity;
import com.dabai.markdownq.ui.MdHelpActivity;
import com.dabai.markdownq.ui.SettingsActivity;
import com.dabai.markdownq.utils.ComparatorByLastModified;
import com.dabai.markdownq.utils.OtherUtils;
import com.dabai.uitools.utils.DisplayUtils;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputLayout;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Objects;

public class MainActivity extends AppCompatActivity {

    ActivityMainBinding amb;
    Context context;

    ActionBarDrawerToggle mToggle;

    long tmpDirSize = 0;
    int tmpDirFileNum = 0;
    private LinearLayoutManager linearLayoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        amb = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(amb.getRoot());

        context = this;

        initializeInterface();

        eventListeners();

        if (SharedPreferencesUtils.getDefaultSharedPreferences(context).getBoolean("passwordLock", false)) {
            DabaiUtils.jumpPasswordAuthentication(this, 888);
        }

        linearLayoutManager = new LinearLayoutManager(context);

        amb.recyclerView.setLayoutManager(linearLayoutManager);

        amb.recyclerView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));

        refreshList();



    }

    /**
     * 刷新列表
     */
    private void refreshList() {
        File dir = OtherUtils.getMarkdownFilesDir(context);
        File[] files = dir.listFiles();
        assert files != null;
        Arrays.sort(files, new ComparatorByLastModified(false));

        ArrayList<FileData> fileDataList = new ArrayList<>();

        for (File file : files) {
            if (!file.getName().toLowerCase().endsWith(".md")) {
                continue;
            }
            FileData fileData = new FileData();
            fileData.setPath(file.getAbsolutePath());
            fileData.setFileName(file.getName());
            fileDataList.add(fileData);
        }

        FileAdapter fileAdapter;

        fileAdapter = new FileAdapter(fileDataList);

        if (SharedPreferencesUtils.getDefaultSharedPreferences(context).getBoolean("animatedTransitions", false)) {
            fileAdapter.setAnimationEnable(true);
            fileAdapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.ScaleIn);
        }

        amb.recyclerView.setAdapter(fileAdapter);

        View viewEmpty = findViewById(R.id.view_empty);
        if (fileAdapter.getData().size() > 0) {
            viewEmpty.setVisibility(View.GONE);
        } else {
            viewEmpty.setVisibility(View.VISIBLE);
        }

        //item单击
        fileAdapter.setOnItemClickListener((adapter, view, position) -> {
            FileData fileData = (FileData) adapter.getData().get(position);
            toEditor(view, "content", fileData.getPath(), true);
        });


        //item长按
        fileAdapter.setOnItemLongClickListener((adapter, view, position) -> {

            FileData fileData = (FileData) adapter.getData().get(position);
            File soc = new File(fileData.getPath());

            String content = FileUtils.readText(soc);

            if (content.isEmpty()) {
                PopupMenuUtils.showPopupMenu(context, view, R.menu.main_item_long, new PopupMenuUtils.OnItemListener() {
                    @Override
                    public void clickItem(MenuItem item) {

                        switch (item.getTitle().toString()) {
                            case "分享":
                                ShareUtils.shareFile(context,
                                        FileProvider.getUriForFile(context, getPackageName() + ".fileProvider", soc),
                                        "*/*");
                                break;
                            case "重命名":
                                AlertDialog alertDialog = MdcDialog.showInputDialog(context, "重命名", StringUtils.removeFileSuffix(soc.getName()), "请输入文件名", new MdcDialog.OnInputDialogButtonListener() {
                                    @Override
                                    public void confirm(AlertDialog dialog, String content) {
                                        File tag1 = new File(soc.getParentFile(), content.replace(" ", "") + ".md");

                                        if (checkFileName(content, tag1)) {
                                            if (soc.renameTo(tag1)) {
                                                DBToast.showText(context, "重命名成功!", true);
                                                refreshList();
                                                dialog.dismiss();
                                            } else {
                                                DBToast.showText(context, "重命名失败!", false);
                                            }
                                        }
                                    }

                                    @Override
                                    public void cancel() {
                                    }
                                });
                                TextInputLayout textInputLayout = alertDialog.findViewById(R.id.til1);
                                assert textInputLayout != null;
                                EditText editText = textInputLayout.getEditText();
                                assert editText != null;
                                editText.setSingleLine(true);
                                alertDialog.getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_IOS);


                                break;
                            case "复制":

                                File tag2 = new File(soc.getParentFile(), DateUtils.getNowTime("hhmmss") + "_" + soc.getName());

                                FileData fileData1 = new FileData();
                                fileData1.setPath(tag2.getAbsolutePath());
                                fileData1.setFileName(tag2.getName());
                                boolean isCopy = FileUtils.copyFile(soc, tag2, true);
                                DBToast.showText(context, isCopy ? "复制成功!" : "复制失败!", isCopy);
                                if (isCopy) {
                                    adapter.addData(0, fileData1);
                                    linearLayoutManager.scrollToPosition(0);
                                }

                                break;
                            case "归档":
                                File tag3 = new File(OtherUtils.getRecoveryDir(context), soc.getName());

                                if (tag3.exists()) {
                                    tag3 = new File(OtherUtils.getRecoveryDir(context), DateUtils.getNowTime("hhmmss") + "_" + soc.getName());
                                }

                                boolean isDel = soc.renameTo(tag3);
                                DBToast.showText(context, isDel ? "归档成功!" : "归档失败!", isDel);
                                if (isDel) {
                                    adapter.remove(fileData);
                                }
                                break;
                            default:
                                break;
                        }
                    }

                    @Override
                    public void onDismiss(PopupMenu menu) {
                    }
                });

            } else {

                //触感反馈
                NotificationUtils.performHapticFeedback(view);

                View dia_view = getLayoutInflater().inflate(R.layout.dialog_preview, null);

                NestedScrollView nestedScrollView = dia_view.findViewById(R.id.nestedScrollView);

                if (DisplayUtils.getScreenHeight(context)>=1920 && DisplayUtils.getScreenDpi(context) <= 440) {

                    LinearLayout.LayoutParams linearParams =(LinearLayout.LayoutParams) nestedScrollView.getLayoutParams();
                    linearParams.height = DisplayUtils.dip2px(context, 400);
                    nestedScrollView.setLayoutParams(linearParams);

                }

                AlertDialog dia_preview = new MaterialAlertDialogBuilder(context)
                        .setTitle(fileData.getFileName())
                        .setView(dia_view)
                        .show();

                dia_preview.getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Scale);

                TextView md_preview = dia_view.findViewById(R.id.preview_textView2);
                OtherUtils.parseMd(context, md_preview, content);

                ImageButton md_preview_share = dia_view.findViewById(R.id.md_preview_share);
                ImageButton md_preview_info = dia_view.findViewById(R.id.md_preview_info);
                ImageButton md_preview_rename = dia_view.findViewById(R.id.md_preview_rename);
                ImageButton md_preview_copy = dia_view.findViewById(R.id.md_preview_copy);
                ImageButton md_preview_del = dia_view.findViewById(R.id.md_preview_del);

                md_preview_share.setOnClickListener(v -> {
                    dia_preview.dismiss();
                    ShareUtils.shareFile(context,
                            FileProvider.getUriForFile(context, getPackageName() + ".fileProvider", soc),
                            "*/*");
                });
                md_preview_info.setOnClickListener(v -> {
                    dia_preview.dismiss();
                    new MaterialAlertDialogBuilder(context)
                            .setTitle("文件信息")
                            .setMessage("文件名:" + fileData.getFileName()
                                    + "\n字数:" + FileUtils.readText(fileData.getPath()).length()
                                    + "\n文件大小:" + FileUtils.getFileSizeString(soc)
                                    + "\n编码方式:" + FileUtils.getFileCharset(soc)
                                    + "\n最后修改时间:" + DateUtils.humanInterval(new Date(soc.lastModified())))
                            .setPositiveButton("确认", null)
                            .show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_IOS);

                });
                md_preview_rename.setOnClickListener(v -> {
                    dia_preview.dismiss();
                    AlertDialog alertDialog = MdcDialog.showInputDialog(context, "重命名", StringUtils.removeFileSuffix(soc.getName()), "请输入文件名", new MdcDialog.OnInputDialogButtonListener() {
                        @Override
                        public void confirm(AlertDialog dialog, String content) {
                            File tag1 = new File(soc.getParentFile(), content.replace(" ", "") + ".md");

                            if (checkFileName(content, tag1)) {
                                if (soc.renameTo(tag1)) {
                                    DBToast.showText(context, "重命名成功!", true);
                                    refreshList();
                                    dialog.dismiss();
                                } else {
                                    DBToast.showText(context, "重命名失败!", false);
                                }
                            }
                        }

                        @Override
                        public void cancel() {
                        }
                    });

                    TextInputLayout textInputLayout = alertDialog.findViewById(R.id.til1);
                    assert textInputLayout != null;
                    EditText editText = textInputLayout.getEditText();
                    assert editText != null;
                    editText.setSingleLine(true);
                    alertDialog.getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_IOS);

                });
                md_preview_copy.setOnClickListener(v -> {

                    dia_preview.dismiss();
                    File tag2 = new File(soc.getParentFile(), DateUtils.getNowTime("hhmmss") + "_" + soc.getName());

                    FileData fileData1 = new FileData();
                    fileData1.setPath(tag2.getAbsolutePath());
                    fileData1.setFileName(tag2.getName());
                    boolean isCopy = FileUtils.copyFile(soc, tag2, true);
                    DBToast.showText(context, isCopy ? "复制成功!" : "复制失败!", isCopy);
                    if (isCopy) {
                        adapter.addData(0, fileData1);
                        linearLayoutManager.scrollToPosition(0);
                    }

                });
                md_preview_del.setOnClickListener(v -> {
                    dia_preview.dismiss();
                    File tag3 = new File(OtherUtils.getRecoveryDir(context), soc.getName());

                    if (tag3.exists()) {
                        tag3 = new File(OtherUtils.getRecoveryDir(context), DateUtils.getNowTime("hhmmss") + "_" + soc.getName());
                    }

                    boolean isDel = soc.renameTo(tag3);
                    DBToast.showText(context, isDel ? "归档成功!" : "归档失败!", isDel);
                    if (isDel) {
                        adapter.remove(fileData);
                    }
                });

            }

            return true;
        });

        tmpDirSize = FileUtils.getFileSize(OtherUtils.getMarkdownFilesDir(context));
        tmpDirFileNum = Objects.requireNonNull(OtherUtils.getMarkdownFilesDir(context).listFiles()).length;

        amb.swipeRefreshLayout.setRefreshing(false);
    }


    /**
     * 跳转到编辑器
     *
     * @param path 路径
     */
    public void toEditor(View view, String transitionName, String path, boolean isFile) {
        Intent intent = new Intent(this, EditorActivity.class);
        intent.putExtra("path", path);
        intent.putExtra("isFile", isFile);
        if (SharedPreferencesUtils.getDefaultSharedPreferences(context).getBoolean("animatedTransitions", false)) {
            ActivityUtils.startActivity(this, intent, view, transitionName);
        } else {
            startActivity(intent);
        }

    }

    /**
     * 跳转到编辑器
     *
     * @param path 路径
     */
    public void toEditor(String path, boolean isFile) {
        Intent intent = new Intent(this, EditorActivity.class);
        intent.putExtra("path", path);
        intent.putExtra("isFile", isFile);
        startActivity(intent);
        if (SharedPreferencesUtils.getDefaultSharedPreferences(context).getBoolean("animatedTransitions", false)) {
            overridePendingTransition(com.dabai.uitools.R.anim.push_ios_in, com.dabai.uitools.R.anim.push_ios_out);
        }
    }

    /**
     * 点击事件监听器
     */
    @SuppressLint("NonConstantResourceId")
    private void eventListeners() {


        amb.navView.setNavigationItemSelectedListener(item -> {
            switch (item.getItemId()) {
                case R.id.newFile:
                    createFile(Gravity.TOP);
                    break;
                case R.id.openFile:
                    SAFUtils.openFile(this, "text/*", 201);
                    if (SharedPreferencesUtils.getDefaultSharedPreferences(context).getBoolean("animatedTransitions", false)) {
                        overridePendingTransition(com.dabai.uitools.R.anim.push_ios_in, com.dabai.uitools.R.anim.push_ios_out);
                    }
                    break;
                case R.id.helpText:
                    //DabaiUtils.openLink(context, "https://www.jianshu.com/p/191d1e21f7ed");
                    ActivityUtils.startActivity(this, MdHelpActivity.class);
                    if (SharedPreferencesUtils.getDefaultSharedPreferences(context).getBoolean("animatedTransitions", false)) {
                        overridePendingTransition(com.dabai.uitools.R.anim.push_ios_in, com.dabai.uitools.R.anim.push_ios_out);
                    }
                    break;
                case R.id.setting:
                    ActivityUtils.startActivity(context, SettingsActivity.class);
                    if (SharedPreferencesUtils.getDefaultSharedPreferences(context).getBoolean("animatedTransitions", false)) {
                        overridePendingTransition(com.dabai.uitools.R.anim.push_ios_in, com.dabai.uitools.R.anim.push_ios_out);
                    }
                    break;
                default:
                    break;
            }
            amb.drawerLayout.closeDrawers();
            return true;
        });

        amb.createFileButton.setOnClickListener(v -> createFile(Gravity.BOTTOM));
        amb.createFileButton.setOnLongClickListener(v -> {

            String fileName = DateUtils.getNowTime(SharedPreferencesBasicUse.getString("rapidNamingNew", "新文件ddhhmmss"));
            File file = new File(OtherUtils.getMarkdownFilesDir(context), fileName + ".md");

            try {
                if (file.createNewFile()) {
                    DBToast.showText(context, "快速创建:"+fileName, true);
                    // refreshList();
                    toEditor(file.getAbsolutePath(), true);
                } else {
                    DBToast.showText(context, "创建失败!", false);
                }

            } catch (IOException e) {
                DBToast.showText(context, "创建失败:" + e.getMessage(), false);
            }

            return true;
        });

        amb.swipeRefreshLayout.setOnRefreshListener(() -> new Handler().postDelayed(this::refreshList, 1000));
        amb.swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.purple_500));

    }


    /**
     * 初始化界面
     */
    private void initializeInterface() {



        setSupportActionBar(amb.toolbar);
        /*设置标题文字不可显示*/
        Objects.requireNonNull(getSupportActionBar()).setDisplayShowTitleEnabled(false);

        mToggle = new ActionBarDrawerToggle(this, amb.drawerLayout, amb.toolbar, R.drawable.ic_baseline_menu_24, R.drawable.ic_baseline_arrow_back_24) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);

            }
        };
        amb.drawerLayout.addDrawerListener(mToggle);
        amb.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNDEFINED);
        mToggle.syncState();/*同步状态*/
    }


    // 用来计算返回键的点击间隔时间
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {

            if (amb.drawerLayout.isDrawerOpen(GravityCompat.START)) {
                amb.drawerLayout.closeDrawer(GravityCompat.START);
                return true;
            }

            if ((System.currentTimeMillis() - exitTime) > 2000) {
                //弹出提示，可以有多种方式
                DBToast.showText(context, "再按一次退出程序", false);
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }


    /**
     * 创建文件
     */
    public void createFile(int gravity) {

        AlertDialog alertDialog = MdcDialog.showInputDialog(context, "新建Markdown文件", "", "请输入文件名", new MdcDialog.OnInputDialogButtonListener() {
            @Override
            public void confirm(AlertDialog dialog, String content) {

                File file = new File(OtherUtils.getMarkdownFilesDir(context), content.replace(" ", "") + ".md");

                if (checkFileName(content, file)) {
                    try {
                        if (file.createNewFile()) {
                            DBToast.showText(context, "创建成功!", true);
                            // refreshList();
                            toEditor(file.getAbsolutePath(), true);
                        } else {
                            DBToast.showText(context, "创建失败!", false);
                        }
                        dialog.dismiss();
                    } catch (IOException e) {
                        dialog.dismiss();
                        DBToast.showText(context, "创建失败:" + e.getMessage(), false);
                    }
                }
            }

            @Override
            public void cancel() {

            }
        });

        alertDialog.getWindow().setWindowAnimations(com.dabai.uitools.R.style.Animation_AppCompat_DropDownUp);
        alertDialog.getWindow().setGravity(gravity);

        TextInputLayout textInputLayout = alertDialog.findViewById(R.id.til1);
        assert textInputLayout != null;
        EditText editText = textInputLayout.getEditText();
        assert editText != null;
        editText.setSingleLine(true);

    }

    private boolean checkFileName(String content, File file) {
        if (!Objects.requireNonNull(file.getParentFile()).exists()) {
            file.getParentFile().mkdirs();
        }

        if (content.toLowerCase().contains(".md")) {
            DBToast.showText(context, "文件名不能包含后缀!", false);
            return false;
        } else if (content.trim().length() <= 0) {
            DBToast.showText(context, "请输入文件名!", false);
            return false;
        } else if (file.exists()) {
            DBToast.showText(context, "该文件名已存在!", false);
            return false;
        } else {
            return true;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();

        SharedPreferencesBasicUse.init(context);
        SharedPreferencesBasicUse.setLong("lastOpen",new Date().getTime());

        if (tmpDirFileNum != Objects.requireNonNull(OtherUtils.getMarkdownFilesDir(context).listFiles()).length || tmpDirSize != FileUtils.getFileSize(OtherUtils.getMarkdownFilesDir(context))) {
            refreshList();
        }

    }


    /**
     * 对活动结果回调
     *
     * @param requestCode 请求的代码
     * @param resultCode  结果代码
     * @param data        数据
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //指纹验证结果
        if (resultCode == RESULT_CANCELED && requestCode == 888) {
            DBToast.showText(context, "身份验证失败!", false);
            finish();
        }

        //打开文件返回结果
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 201) {
                if (data != null) {
                    toEditor(data.getDataString(), false);
                }
            }
        }

    }




}